/**
 * ConversationModel - 对话模型类
 * 基于 Augment Code 的对话管理机制
 */

import { EventEmitter } from 'events';
import { 
  ConversationContext, 
  Turn, 
  TurnStatus, 
  ChatMode, 
  StructuredNode, 
  NodeType,
  SendRequest,
  AgentMemory,
  CodeContext,
  ToolType
} from './types';
import { PromptBuilder } from './prompt-builder';

export class ConversationModel extends EventEmitter {
  private context: ConversationContext;
  private promptBuilder: PromptBuilder;
  private currentTurn: Turn | null = null;

  constructor(
    conversationId: string,
    mode: ChatMode = ChatMode.CHAT,
    promptBuilder?: PromptBuilder
  ) {
    super();
    
    this.context = {
      id: conversationId,
      mode,
      turns: [],
      memories: [],
      activeTools: [],
      metadata: {}
    };
    
    this.promptBuilder = promptBuilder || new PromptBuilder();
  }

  /**
   * 发送消息并开始新的对话轮次
   */
  async sendMessage(request: SendRequest): Promise<string> {
    const requestId = this.generateRequestId();
    
    // 创建新的对话轮次
    const turn: Turn = {
      id: this.generateTurnId(),
      requestId,
      status: TurnStatus.Sent,
      requestMessage: request.requestMessage,
      nodes: []
    };

    this.currentTurn = turn;
    this.context.turns.push(turn);
    
    this.emit('turnStarted', turn);
    
    try {
      // 构建提示词
      const prompt = this.promptBuilder.buildPrompt(
        request.requestMessage,
        this.context
      );
      
      this.emit('promptGenerated', { prompt, requestId });
      
      return requestId;
    } catch (error) {
      turn.status = TurnStatus.Failed;
      this.emit('turnFailed', { turn, error });
      throw error;
    }
  }

  /**
   * 添加结构化节点到当前轮次
   */
  addNode(node: StructuredNode): void {
    if (!this.currentTurn) {
      throw new Error('No active turn to add node to');
    }

    this.currentTurn.nodes.push(node);
    this.emit('nodeAdded', { turn: this.currentTurn, node });

    // 根据节点类型处理特殊逻辑
    this.handleSpecialNodeTypes(node);
  }

  /**
   * 完成当前轮次
   */
  completeTurn(status: TurnStatus = TurnStatus.Success): void {
    if (!this.currentTurn) {
      throw new Error('No active turn to complete');
    }

    this.currentTurn.status = status;
    this.emit('turnCompleted', this.currentTurn);
    this.currentTurn = null;
  }

  /**
   * 取消当前轮次
   */
  cancelTurn(): void {
    if (this.currentTurn) {
      this.currentTurn.status = TurnStatus.Cancelled;
      this.emit('turnCancelled', this.currentTurn);
      this.currentTurn = null;
    }
  }

  /**
   * 重新发送轮次
   */
  async resendTurn(turn: Turn): Promise<string> {
    const request: SendRequest = {
      requestMessage: turn.requestMessage
    };
    
    return this.sendMessage(request);
  }

  /**
   * 设置聊天模式
   */
  setChatMode(mode: ChatMode): void {
    this.context.mode = mode;
    this.emit('modeChanged', mode);
  }

  /**
   * 更新代码上下文
   */
  updateCodeContext(codeContext: CodeContext): void {
    this.context.codeContext = codeContext;
    this.emit('codeContextUpdated', codeContext);
  }

  /**
   * 添加记忆
   */
  addMemory(memory: AgentMemory): void {
    this.context.memories.push(memory);
    this.emit('memoryAdded', memory);
  }

  /**
   * 更新记忆状态
   */
  updateMemoryState(memoryId: string, state: AgentMemory['state']): void {
    const memory = this.context.memories.find(m => m.id === memoryId);
    if (memory) {
      memory.state = state;
      this.emit('memoryUpdated', memory);
    }
  }

  /**
   * 激活工具
   */
  activateTools(tools: ToolType[]): void {
    this.context.activeTools = [...new Set([...this.context.activeTools, ...tools])];
    this.emit('toolsActivated', tools);
  }

  /**
   * 停用工具
   */
  deactivateTools(tools: ToolType[]): void {
    this.context.activeTools = this.context.activeTools.filter(
      tool => !tools.includes(tool)
    );
    this.emit('toolsDeactivated', tools);
  }

  /**
   * 获取对话历史
   */
  getConversationHistory(): Turn[] {
    return [...this.context.turns];
  }

  /**
   * 获取当前上下文
   */
  getContext(): ConversationContext {
    return { ...this.context };
  }

  /**
   * 获取当前轮次
   */
  getCurrentTurn(): Turn | null {
    return this.currentTurn;
  }

  /**
   * 获取最后一个成功的轮次
   */
  getLastSuccessfulTurn(): Turn | null {
    return this.context.turns
      .slice()
      .reverse()
      .find(turn => turn.status === TurnStatus.Success) || null;
  }

  /**
   * 清除对话历史
   */
  clearHistory(): void {
    this.context.turns = [];
    this.currentTurn = null;
    this.emit('historyCleared');
  }

  /**
   * 生成建议问题
   */
  async generateSuggestedQuestions(count: number = 3): Promise<string[]> {
    if (this.context.turns.length === 0) return [];
    
    const prompt = this.promptBuilder.buildSuggestedQuestionsPrompt(this.context.turns);
    
    // 这里应该调用 AI 模型生成建议问题
    // 暂时返回示例问题
    return [
      "Can you explain this code in more detail?",
      "How can I improve the performance?",
      "Are there any potential issues I should be aware of?"
    ].slice(0, count);
  }

  /**
   * 处理特殊节点类型
   */
  private handleSpecialNodeTypes(node: StructuredNode): void {
    switch (node.type) {
      case NodeType.MainTextFinished:
        this.emit('mainTextFinished', node);
        break;
      
      case NodeType.SuggestedQuestions:
        this.emit('suggestedQuestionsGenerated', node);
        break;
      
      case NodeType.ToolUse:
        this.emit('toolUseCompleted', node);
        break;
      
      case NodeType.ToolUseStart:
        this.emit('toolUseStarted', node);
        break;
      
      case NodeType.AgentMemory:
        this.emit('memoryNodeAdded', node);
        break;
      
      case NodeType.Thinking:
        this.emit('thinkingNodeAdded', node);
        break;
    }
  }

  /**
   * 生成请求ID
   */
  private generateRequestId(): string {
    return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 生成轮次ID
   */
  private generateTurnId(): string {
    return `turn_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 设置元数据
   */
  setMetadata(key: string, value: any): void {
    this.context.metadata = this.context.metadata || {};
    this.context.metadata[key] = value;
    this.emit('metadataUpdated', { key, value });
  }

  /**
   * 获取元数据
   */
  getMetadata(key: string): any {
    return this.context.metadata?.[key];
  }

  /**
   * 获取统计信息
   */
  getStats() {
    const turns = this.context.turns;
    const totalTurns = turns.length;
    const successfulTurns = turns.filter(t => t.status === TurnStatus.Success).length;
    const failedTurns = turns.filter(t => t.status === TurnStatus.Failed).length;
    const totalNodes = turns.reduce((sum, turn) => sum + turn.nodes.length, 0);
    
    return {
      totalTurns,
      successfulTurns,
      failedTurns,
      totalNodes,
      successRate: totalTurns > 0 ? successfulTurns / totalTurns : 0,
      activeMemories: this.context.memories.filter(m => m.state === 'accepted').length,
      activeTools: this.context.activeTools.length
    };
  }
}
